package com.gty;

import com.alibaba.fastjson.JSON;

import com.gty.controller.UserController;
import com.gty.entity.UserHero;
import com.gty.lolutil.BaseUtil;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.*;
import java.io.*;
import java.net.URI;
import java.util.*;

public class MyCmd {
    public static void main(String[] args) throws Exception {
        MyCmd myCmd = new MyCmd();
        final UserController userController = new UserController();
        String res = myCmd.executive("wmic PROCESS WHERE name='LeagueClientUx.exe' GET commandline");
        Map<String, String> map = myCmd.getToken(res);

        //DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

        String username = "riot";
        final String port = map.get("port");
        String password = map.get("token");
        final String baseUrl = "https://127.0.0.1:";

        String url = baseUrl + port + "+/lol-summoner/v1/current-summoner";
        URI uri = new URI(url);
        final CloseableHttpClient ignoreSSLClient = BaseUtil.getIgnoreSSLClient(password, uri.getPort());
        System.err.println(uri.getHost());


        //获取召唤师id
        long summonerId = userController.getSummonerId(baseUrl + port, ignoreSSLClient);
        System.out.println("召唤师id==" + summonerId);
        //获取召唤师基本数据
        Scanner scanner = new Scanner(System.in);
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse result = ignoreSSLClient.execute(httpGet);
        System.out.println(result.getStatusLine());
        System.out.println();
        //获取结果
        String json = BaseUtil.getJson(result.getEntity().getContent());
        System.err.println("当前召唤师数据=="+json);
        //待补充json字符串转实体类

        //获取用户当前所有可用英雄
        List<UserHero> userAllHero = userController.getUserAllHero(baseUrl + port, ignoreSSLClient);
        System.out.println("用户当前所有可用英雄====");
        for(UserHero u:userAllHero){
            System.out.println(u);
        }
        System.out.println("请输入选择英雄id");

        //监听 开个定时器轮询
        final Boolean[] flag = {false};
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               //减少无效http请求资源浪费
                                  //System.out.println("轮询=====");
                                   CloseableHttpResponse execute = null, accept = null;
                                   try {
                                       execute = ignoreSSLClient.execute(new HttpGet(baseUrl + port + "/lol-matchmaking/v1/ready-check"));
                                       if (execute.getStatusLine().getStatusCode() == 200) {
                                           //System.err.println("200");
                                           //开始判断内部字段
                                           InputStream in = execute.getEntity().getContent();
                                           String json = BaseUtil.getJson(in);
                                           Map map1 = JSON.parseObject(json, Map.class);
                                           if ("InProgress".equals(map1.get("state"))) {
                                               //System.err.println("发送秒进请求");
                                               accept=ignoreSSLClient.execute(new HttpPost(baseUrl + port + "/lol-matchmaking/v1/ready-check/accept"));
                                               System.out.println("秒进响应码=="+accept.getStatusLine().getStatusCode());
                                               flag[0] = true;
                                           }
                                       }
                                   } catch (Exception e) {
                                       e.printStackTrace();
                                   } finally {
                                       try {
                                           execute.close();
                                           if (accept != null)
                                               accept.close();
                                       } catch (IOException e) {
                                           e.printStackTrace();
                                       }
                                   }
                               }


                       }
                , new Date(), 1000);

        BaseUtil.HERO_ID = scanner.next();
        //开一个秒选英雄的定时任务
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                //true
                    //System.out.println("秒选英雄");
                    userController.instantSelectHero(baseUrl + port, ignoreSSLClient, BaseUtil.HERO_ID);
                    //flag[0] = false;

            }
        }, new Date(), 1000);

        while (true) {
            List<UserHero> u = userController.getUserAllHero(baseUrl + port, ignoreSSLClient);
            if(u!=null){
                for (UserHero userHero : u) {
                    System.out.println(userHero.toString());
                }
            }
            System.out.println("想更换秒选英雄就重新输入");
            BaseUtil.HERO_ID = scanner.next();
        }
    }

    /**
     * 执行cmd 命令 获取带有token和port的超长字符串
     *
     * @param stmt
     * @return
     */
    public  String executive(String stmt) {
        Runtime runtime = Runtime.getRuntime();

        String[] command = {"cmd", "/c", stmt};
        BufferedReader bis = null;
        Process process;
        try {

            process = runtime.exec(stmt);

            bis = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String s = "";
            StringBuilder sb = new StringBuilder();
            while ((s = bis.readLine()) != null) {
                System.err.println(s);
                sb.append(s);
            }

            System.out.println(sb.toString());
            System.out.println(process.waitFor() + "--0就执行成功");
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "";
    }

    /**
     * 获取远程端口号 和token
     *
     * @param str
     * @return
     */
    public  Map<String, String> getToken(String str) {
        Map<String, String> map = new HashMap();

        String[] res = str.split(" ");
        //System.out.println(Arrays.toString(res));
        for (String s : res) {
            if (s.contains("--app-port")) {
                String[] split = s.split("=");
                map.put("port", split[1].substring(0, split[1].length() - 1));
            } else if (s.contains("--remoting-auth-token")) {
                String[] split = s.split("=");
                map.put("token", split[1].substring(0, split[1].length() - 1));
            }
        }
        System.out.println(map.get("token"));
        System.out.println(map.get("port"));

        return map;
    }


}
